package com.qzdatasoft.ratelimit.adapter.impl;

import com.qzdatasoft.ratelimit.adapter.ClientInfoExtractor;
import jakarta.servlet.http.HttpServletRequest;

/**
 * 默认的客户端信息提取器实现
 */
public class DefaultClientInfoExtractor implements ClientInfoExtractor {

    @Override
    public String extractClientIp(HttpServletRequest request) {
        // 从X-Forwarded-For头部获取真实IP（适用于反向代理场景）
        String xForwardedFor = request.getHeader("X-Forwarded-For");
        if (xForwardedFor != null && !xForwardedFor.isEmpty() && !"unknown".equalsIgnoreCase(xForwardedFor)) {
            // 取第一个IP（客户端真实IP）
            String[] ips = xForwardedFor.split(",");
            return ips[0].trim();
        }

        // 从X-Real-IP头部获取
        String xRealIp = request.getHeader("X-Real-IP");
        if (xRealIp != null && !xRealIp.isEmpty() && !"unknown".equalsIgnoreCase(xRealIp)) {
            return xRealIp;
        }

        // 从Proxy-Client-IP头部获取
        String proxyClientIp = request.getHeader("Proxy-Client-IP");
        if (proxyClientIp != null && !proxyClientIp.isEmpty() && !"unknown".equalsIgnoreCase(proxyClientIp)) {
            return proxyClientIp;
        }

        // 从WL-Proxy-Client-IP头部获取
        String wlProxyClientIp = request.getHeader("WL-Proxy-Client-IP");
        if (wlProxyClientIp != null && !wlProxyClientIp.isEmpty() && !"unknown".equalsIgnoreCase(wlProxyClientIp)) {
            return wlProxyClientIp;
        }

        // 最后从RemoteAddr获取
        return request.getRemoteAddr();
    }

    @Override
    public String extractUserId(HttpServletRequest request) {
        // 从认证信息中提取用户ID
        // 这里可以根据具体的认证框架（如Spring Security）进行扩展
        if (request.getUserPrincipal() != null) {
            return request.getUserPrincipal().getName();
        }

        // 从自定义头部获取用户ID
        String userIdHeader = request.getHeader("X-User-Id");
        if (userIdHeader != null && !userIdHeader.isEmpty()) {
            return userIdHeader;
        }

        // 从参数中获取用户ID（适用于某些场景）
        String userIdParam = request.getParameter("userId");
        if (userIdParam != null && !userIdParam.isEmpty()) {
            return userIdParam;
        }

        // 无法获取用户ID
        return null;
    }

    @Override
    public boolean isOwner(String urlPatten) {
        return true;
    }
}
